/**
 * 
 */
package com.simtek.simplayer.utils;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Collections;
import java.util.List;

import org.apache.http.conn.util.InetAddressUtils;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.graphics.Point;
import android.media.AudioManager;
import android.os.Build;
import android.view.Display;
import android.view.Window;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;

/**
 * @author Hitech
 * 
 */
public class SystemUtils {
	@SuppressWarnings("deprecation")
	@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
	public static int[] getDisplaySize(Context context) {
		WindowManager wm = (WindowManager) context
				.getSystemService(Context.WINDOW_SERVICE);
		Display display = wm.getDefaultDisplay();

		int[] res = new int[2];
		if (OsDetectUtils.hasHoneycombMR2()) {
			Point outSize = new Point();
			display.getSize(outSize);
			res[0] = outSize.x;
			res[1] = outSize.y;
		} else {
			res[0] = display.getWidth();
			res[1] = display.getHeight();
		}
		return res;
	}

	/**
	 * @param context
	 * @param streamType
	 * <br>
	 *            {@link AudioManager#STREAM_MUSIC}<br>
	 *            {@link AudioManager#STREAM_ALARM}<br>
	 *            {@link AudioManager#STREAM_NOTIFICATION}<br>
	 *            {@link AudioManager#STREAM_RING}<br>
	 *            {@link AudioManager#STREAM_SYSTEM}<br>
	 *            {@link AudioManager#STREAM_VOICE_CALL}
	 * @return MaxVolumn
	 */
	public static int getMaxVolume(Context context, int streamType) {
		AudioManager audioManager = (AudioManager) context
				.getSystemService(Context.AUDIO_SERVICE);
		return audioManager.getStreamMaxVolume(streamType);
	}

	/**
	 * @param context
	 * @param streamType
	 * <br>
	 *            {@link AudioManager#STREAM_MUSIC}<br>
	 *            {@link AudioManager#STREAM_ALARM}<br>
	 *            {@link AudioManager#STREAM_NOTIFICATION}<br>
	 *            {@link AudioManager#STREAM_RING}<br>
	 *            {@link AudioManager#STREAM_SYSTEM}<br>
	 *            {@link AudioManager#STREAM_VOICE_CALL}
	 * @return MaxVolumn
	 */
	public static int getVolume(Context context, int streamType) {
		AudioManager audioManager = (AudioManager) context
				.getSystemService(Context.AUDIO_SERVICE);
		return audioManager.getStreamVolume(streamType);
	}

	/**
	 * @param context
	 * @param streamType
	 * <br>
	 *            {@link AudioManager#STREAM_MUSIC}<br>
	 *            {@link AudioManager#STREAM_ALARM}<br>
	 *            {@link AudioManager#STREAM_NOTIFICATION}<br>
	 *            {@link AudioManager#STREAM_RING}<br>
	 *            {@link AudioManager#STREAM_SYSTEM}<br>
	 *            {@link AudioManager#STREAM_VOICE_CALL}
	 * @return
	 */
	public static boolean setVolumePercent(Context context, int streamType,
			float percent) {
		if (percent < 0 || percent > 100) {
			return false;
		}

		AudioManager audioManager = (AudioManager) context
				.getSystemService(Context.AUDIO_SERVICE);
		audioManager
				.setStreamVolume(streamType,
						(int) (audioManager.getStreamMaxVolume(streamType)
								* percent / 100), 0);
		return true;
	}

	/**
	 * @param context
	 * @param streamType
	 * <br>
	 *            {@link AudioManager#STREAM_MUSIC}<br>
	 *            {@link AudioManager#STREAM_ALARM}<br>
	 *            {@link AudioManager#STREAM_NOTIFICATION}<br>
	 *            {@link AudioManager#STREAM_RING}<br>
	 *            {@link AudioManager#STREAM_SYSTEM}<br>
	 *            {@link AudioManager#STREAM_VOICE_CALL}
	 * @return MaxVolumn
	 */
	public static float seekVolumeByPercent(Context context, int streamType,
			float percent) {
		AudioManager audioManager = (AudioManager) context
				.getSystemService(Context.AUDIO_SERVICE);
		int max = audioManager.getStreamMaxVolume(streamType);
		int current = audioManager.getStreamVolume(streamType);

		float currentPercent = current * 100 / max;
		float newPercent = currentPercent + percent;
		newPercent = Math.min(Math.max(0, newPercent), 100);

		int nVolume = (int) (currentPercent + percent) * max / 100;
		audioManager.setStreamVolume(streamType, nVolume, 0);

		return newPercent;
	}

	/**
	 * @param context
	 * @param streamType
	 * <br>
	 *            {@link AudioManager#STREAM_MUSIC}<br>
	 *            {@link AudioManager#STREAM_ALARM}<br>
	 *            {@link AudioManager#STREAM_NOTIFICATION}<br>
	 *            {@link AudioManager#STREAM_RING}<br>
	 *            {@link AudioManager#STREAM_SYSTEM}<br>
	 *            {@link AudioManager#STREAM_VOICE_CALL}
	 * @return MaxVolumn
	 */
	public static float getVolumePercent(Context context, int streamType) {
		AudioManager audioManager = (AudioManager) context
				.getSystemService(Context.AUDIO_SERVICE);
		int streamMaxVolume = audioManager.getStreamMaxVolume(streamType);
		int current = audioManager.getStreamVolume(streamType);

		return current * 100 / streamMaxVolume;
	}

	/**
	 * @param activity
	 * @return ScreenBrightness [0,1]
	 */
	public static float getActivityScreenBrightness(Activity activity) {
		return activity.getWindow().getAttributes().screenBrightness;
	}

	/**
	 * @param activity
	 * @param value
	 *            [0,1]
	 * @return
	 */
	public static void setActivityScreenBrightness(Activity activity,
			float value) {
		Window window = activity.getWindow();
		LayoutParams attributes = window.getAttributes();
		attributes.screenBrightness = Math.min(Math.max(value, 0.05f), 1);
		window.setAttributes(attributes);
	}

	/**
	 * @param activity
	 * @param value
	 *            [0,1]
	 * @return
	 */
	public static float seekActivityScreenBrightness(Activity activity,
			float value) {
		Window window = activity.getWindow();
		LayoutParams attributes = window.getAttributes();
		float newValue = attributes.screenBrightness + value;
		attributes.screenBrightness = Math.min(Math.max(newValue, 0.05f), 1);
		window.setAttributes(attributes);
		return attributes.screenBrightness;
	}

	/**
	 * Returns MAC address of the given interface name.
	 * 
	 * @param interfaceName
	 *            eth0, wlan0 or NULL=use first interface
	 * @return mac address or empty string
	 */
	@TargetApi(Build.VERSION_CODES.GINGERBREAD)
	public static String getMACAddress(String interfaceName) {
		try {
			List<NetworkInterface> interfaces = Collections
					.list(NetworkInterface.getNetworkInterfaces());
			for (NetworkInterface intf : interfaces) {
				if (interfaceName != null) {
					if (!intf.getName().equalsIgnoreCase(interfaceName))
						continue;
				}
				byte[] mac = intf.getHardwareAddress();
				if (mac == null)
					return "";
				StringBuilder buf = new StringBuilder();
				for (int idx = 0; idx < mac.length; idx++)
					buf.append(String.format("%02X:", mac[idx]));
				if (buf.length() > 0)
					buf.deleteCharAt(buf.length() - 1);
				return buf.toString();
			}
		} catch (Exception ex) {
		} // for now eat exceptions
		return "";
		/*
		 * try { // this is so Linux hack return
		 * loadFileAsString("/sys/class/net/" +interfaceName +
		 * "/address").toUpperCase().trim(); } catch (IOException ex) { return
		 * null; }
		 */
	}

	/**
	 * Get IP address from first non-localhost interface
	 * 
	 * @param ipv4
	 *            true=return ipv4, false=return ipv6
	 * @return address or empty string
	 */
	public static String getIPAddress(boolean useIPv4) {
		try {
			List<NetworkInterface> interfaces = Collections
					.list(NetworkInterface.getNetworkInterfaces());
			for (NetworkInterface intf : interfaces) {
				List<InetAddress> addrs = Collections.list(intf
						.getInetAddresses());
				for (InetAddress addr : addrs) {
					if (!addr.isLoopbackAddress()) {
						String sAddr = addr.getHostAddress().toUpperCase();
						boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr);
						if (useIPv4) {
							if (isIPv4)
								return sAddr;
						} else {
							if (!isIPv4) {
								int delim = sAddr.indexOf('%'); // drop ip6 port
																// suffix
								return delim < 0 ? sAddr : sAddr.substring(0,
										delim);
							}
						}
					}
				}
			}
		} catch (Exception ex) {
		} // for now eat exceptions
		return "";
	}
}
